<?php

namespace app\admin\services;


use app\admin\model\ClassifyModel;
use app\admin\model\PurchaseProductModel;
use think\facade\Validate;
use think\db\Expression;

class PurchaseProductService extends BaseService
{

    /**
     * 后台订单列表
     * @param $p
     * @return void
     */
    public static function index($p)
    {
        $params = [
            'where' => self::getListCondition($p),
            'page' => ($p['pageNo']) ?? 1,
            'pageSize' => ($p['pageSize']) ?? 10,
            'order' => ['create_time desc'],
            'with'=>[
                'sku'=>function($q){
                    $q->withField(['id','label']);
                },
                'customer'=>function($q){
                    $q->withField(['id','label']);
                }
            ]
        ];
        $list = PurchaseProductModel::getList($params);
        $count = PurchaseProductModel::count($params['where']);
        api_return(200, '', ['list' => $list, 'total' => $count]);
    }
    /**
     * 订单列表的展示条件，同excel导出订单的条件
     * @param $p get请求/数据库记录的参数
     * @return array[]
     */
    public static function getListCondition($p){
        $where=[

        ];
        if (!empty($p['customer_id']))
            $where[] = ['customer_id', '=',  $p['customer_id'] ];
        if (!empty($p['attribute'])){

            $skuIdList = ClassifyModel::where('label','like','%'.$p['attribute'].'%')->select()->toArray();
            $skuIdList = array_column($skuIdList,'id');
            $where[] = ['sku_id', 'in',  $skuIdList ];
        }

        if (!empty($p['sku_id']))
            $where[] = ['sku_id', 'in', $p['sku_id']];
        if (!empty($p['status']))
            $where[] = ['status', '=', $p['status']];
        if (!empty($p['fromTime'])&&!empty($p['toTime'])) {
            $where[] = ['create_time', '>=', ($p['fromTime'])];
            $where[] = ['create_time', '<=', ($p['toTime']).' 23:59:59'];
        }
        return $where;
    }

    /**
     * 操作订单
     * @return void
     */
    public static function edit($p)
    {
        $rule = [
        ];
        $validate = Validate::rule($rule);
        if (!$validate->check($p))
            api_return(500, $validate->getError());

        $validate=Validate::rule($rule);
        if(!$validate->check($p))
            api_return(500,$validate->getError());
        if(!empty($p['tempPath'])&&!empty($p['fileType'])) {
            $p['file_path']=self::getUploadField($p['tempPath'],$p['fileType'],($p['temp_old'])??null);
        }
        PurchaseProductModel::edit($p);
    }

    public static function del($p){
        $rule=[
            'ids'=>'require',
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p))
            api_return(500,'',$validate->getError());
        PurchaseProductModel::delByIds($p['ids']);
    }

    public static function excel($p){
        $list = PurchaseProductModel::where(self::getListCondition($p))->with([
            'sku'=>function($q){
                $q->withField(['id','label']);
            },
            'customer'=>function($q){
                $q->withField(['id','label']);
            }
        ])->order('create_time desc')->select();
        $title = [
            '采购工单',
            '采购日期',
            'SKU',
            '采购数量',
            '计价单位',
            '采购单价(￥)',
            '采购金额(￥)',
            '单位KWH',
            '总KWH',
            'KWH单价',
            '上游客户',
            '备注',
        ];
        $orgin=[];
        foreach ($list as $i) {
            $item = $i->toArray();
            $orgin[]=[
                $item['label'],
                $item['sale_date'],
                $item['sku']['label'],
                $item['number'],
                $item['unit'],
                $item['unit_price'],
                $item['total_price'],
                $item['unit_kwh'],
                $item['total_kwh'],
                $item['kwh_unit_price'],
                $item['customer']['label'],
                $item['remark'],
            ];
        }
        ExcelService::makeExcel($title,$orgin,'采购工单(产品)');
    }

}
